/**
 * 
 */
package com.asset.salesforce.controller.ajax;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.asset.salesforce.domain.Contact;
import com.asset.salesforce.domain.Employee;
import com.asset.salesforce.domain.Lead;
import com.asset.salesforce.dto.table.LeadData;
import com.asset.salesforce.dto.table.ReadOperationParams;
import com.asset.salesforce.dto.table.ReadOperationResults;
import com.asset.salesforce.service.CalendarService;
import com.asset.salesforce.service.ContactService;
import com.asset.salesforce.service.EmployeeService;
import com.asset.salesforce.service.LeadService;

// TODO: Auto-generated Javadoc
/**
 * The Class LeadRestController.
 *
 * @author Hisham
 */
@Controller
public class LeadRestController {

	/** The lead service. */
	@Autowired
	private LeadService leadService;
	
	/** The employee service. */
	@Autowired
	private  EmployeeService employeeService;
	
	/** The contact service. */
	@Autowired
	private ContactService contactService;
	
	/** The calendar service. */
	@Autowired
	private CalendarService calendarService;
	
	/**
	 * List.
	 *
	 * @param params the params
	 * @param session the session
	 * @return the read operation results
	 */
	@RequestMapping(value = "/leadsList", method = RequestMethod.GET, produces = "application/json")
	public @ResponseBody
	ReadOperationResults list(ReadOperationParams params,HttpSession session) {
		ReadOperationResults result = new ReadOperationResults();
		Employee userDetails = (Employee) session.getAttribute("userDetails");
		
		String sortDir = params.getsSortDir_0();
		String sortColName = params.getsColumns().split(",")[params.getiSortCol_0()];
		String column=null;
		if(sortColName.equals("id")){
			column="id";
		}
		if(sortColName.equals("name")){
			column="fName";
		}
		if(sortColName.equals("leadstatus")){
			column="leadStatus";
		}
		if(sortColName.equals("company")){
			column="companyName";
		}
		if(sortColName.equals("owner")){
			column="leadOwner.fName";
		}
		
		List<Lead>allLeads = new ArrayList<Lead>();
		if(userDetails.getIsOwner()==true){
			allLeads = leadService.getAllLeadByCompany(params.getsSearch(),userDetails.getCompany().getId(), params.getiDisplayStart(), params.getiDisplayLength(),column,sortDir);
			Integer size = leadService.getAllSizeForOwner(params.getsSearch(),userDetails.getCompany().getCompanyName());
			result.setiTotalDisplayRecords(size);
	        result.setiTotalRecords(size);
		}
		else{
			allLeads = leadService.getAllLeadByEmployee(params.getsSearch(),userDetails.getId(), params.getiDisplayStart(), params.getiDisplayLength(),column,sortDir);
			Integer size = leadService.getAllSizeForEmployee(params.getsSearch(),userDetails.getId());
			result.setiTotalDisplayRecords(size);
	        result.setiTotalRecords(size);
		}        
        result.setsEcho(params.getsEcho());
        List<LeadData>leadData = new ArrayList<LeadData>();
		for (Lead lead : allLeads) {
			LeadData data = new LeadData();
			data.setId(lead.getId().toString());
			data.setCompany(lead.getCompanyName());
			data.setName(lead.getfName());
			if(lead.getLeadStatus()!=null&&!lead.getLeadStatus().equalsIgnoreCase("")){
				data.setLeadstatus(lead.getLeadStatus());
			}
			if(lead.getLeadOwner()!=null){
				Employee employee = employeeService.getById(lead.getLeadOwner().getId());
				data.setOwner(employee.getfName()+" "+employee.getlName());
			}
			data.setCheckbox("<input type='checkbox' id='selectall' name='selectall' class = 'selectall' value='"+lead.getId()+"'/>");
			leadData.add(data);
		}
        result.setAaData(leadData);
        return result;
	}
	
	/**
	 * Delete.
	 *
	 * @param session the session
	 * @param model the model
	 * @param request the request
	 * @param response the response
	 * @param id the id
	 * @return true, if successful
	 */
	@RequestMapping(value = "/deleteLead", method = RequestMethod.POST)
	@ResponseBody
	public boolean delete(HttpSession session,Model model,HttpServletRequest request,HttpServletResponse response,@RequestParam Integer[] id) {
		if (SecurityUtils.getSubject().hasRole("leadDelete")){
			try {
				request.setCharacterEncoding("UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}			
			 for (Integer integer : id) {
				 Lead lead = leadService.getById(integer);
				 lead.setIsDeleted(true);
				 lead.setDateModified(new Date());
				 leadService.saveOrUpdate(lead);
				 List<Contact>contacts = contactService.getContactsByParentType(lead.getId(), "lead");
				 if(contacts!=null){
					 for (Contact contact : contacts) {
						 contact.setIsDeleted(true);
						 contact.setDateModified(new Date());
						 contactService.saveOrupdate(contact);
					}
				 }
			 }
			 response.setStatus(HttpServletResponse.SC_OK);
				return true;
			}
			else{
				response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
				return false;
			}	
	}
}
